<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import ip from '@/utils/baseURL.js'

const route = useRoute()
const newsDetail = ref({
    title: '',
    mainBody: '',
    time: []
})

// 格式化时间数组为字符串
const formatTime = (timeArr) => {
    if (!timeArr || !Array.isArray(timeArr) || timeArr.length < 3) return '-';
    const [year, month, day] = timeArr;
    // 补充前导零
    const formattedMonth = String(month).padStart(2, '0');
    const formattedDay = String(day).padStart(2, '0');
    return `${year}年${formattedMonth}月${formattedDay}日`;
}

const fetchNewsDetail = async () => {
    try {
        const id = route.query.id
        const response = await axios.get(`${ip}/inter/journalism/getJournalismById`, {
            params: { id }
        })
        
        if (response.data.code === 200) {
            newsDetail.value = response.data.data
        }
    } catch (error) {
        console.error('获取新闻详情失败:', error)
    }
}

onMounted(() => {
    fetchNewsDetail()
})
</script>

<template>
    <div class="news-detail-container">
        <div class="news-content">
            <h1 class="title">{{ newsDetail.title }}</h1>
            <div class="meta-info">
                <span class="time">发布时间：{{ formatTime(newsDetail.time) }}</span>
            </div>
            <div class="content">
                <!-- 使用 white-space: pre-wrap 来保留换行符 -->
                <p class="main-body">{{ newsDetail.mainBody }}</p>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.news-detail-container {
    max-width: 800px;
    margin: 20px auto;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.news-content {
    .title {
        font-size: 24px;
        color: #333;
        margin-bottom: 20px;
        text-align: center;
    }

    .meta-info {
        text-align: center;
        margin-bottom: 30px;
        
        .time {
            color: #999;
            font-size: 14px;
        }
    }

    .content {
        padding: 20px;
        line-height: 1.8;
        
        .main-body {
            white-space: pre-wrap; /* 保留换行符 */
            color: #333;
            font-size: 16px;
            margin: 0;
        }
    }
}
</style>